<?php


namespace app\astrologer\controller\v4;

use app\astrologer\controller\AstrAuth;
use app\common\cachemodel\ZlcrAstrAccount;
use app\common\lib\Util;
use think\Db;

/**
 * Class Earnings
 * @support v2.0.0
 * @package app\astrologer\controller
 */
class Earnings extends AstrAuth
{
    /**
     * 获取列表数据
     * @method GET
     */
    public function list()
    {
        $param['page'] = $this->request->param('page/d', 1);
        $param['limit'] = $this->request->param('limit/d', 10);
        //h5
        $param['start_time'] = $this->request->param('start_time/s', 0);
        $param['end_time'] = $this->request->param('end_time/s', 0);
        //pc
        $rangeTime = input('range_time/a', []);
        $isTeam = input('is_team/d', 0);
        $param['question'] = $this->request->param('question/s', '');
        $param['qtype'] = $this->request->only(['qtype']);
        $param['status'] = $this->request->only(['status']);
        $questionType = input('question_type/d', 0); // 0=>不筛选 1=>定制报告 2=>问答

        $accountInfo = (new ZlcrAstrAccount())->getAstrAccountInfo($this->astrInfo['id'], ['balance', 'total_amount']);
        $teamId = $this->astrInfo['team_id'] ?? 0;
        if ($isTeam === 1 && !$teamId)
        {
            return show(config('code.error'), '服务异常，请稍后再试');
        }
        $where = [];
        if ($isTeam === 1)
        {
            $where['a.team_id'] = $teamId;
        } else
        {
            $where['a.team_id'] = 0;
        }
        if (!empty($rangeTime))
        {
            if (!empty($rangeTime[0]) && !empty($rangeTime[1]))
            {
                // 前端组件，肯定有这两个参数
                $where['a.create_time'] = ['between', [strtotime($rangeTime[0]), strtotime($rangeTime[1])]];
            }
        } else if (($param['start_time'] && $param['end_time']))
        {
            $start_time = strtotime($param['start_time']);
            $end_time = strtotime($param['end_time']);
            if ($end_time < $start_time)
            {
                return show(0, '开始时间不能大于结束时间！');
            } else
            {
                $where['a.create_time'] = ['between', [$start_time, $end_time]];
            }

        } else if ($param['start_time'])
        {
            $start_time = strtotime($param['start_time']);
            $where['a.create_time'] = ['>=', $start_time];
        } else if ($param['end_time'])
        {
            $where['a.create_time'] = ['<', strtotime($param['start_time'])];
        }
        switch ($questionType)
        {
            case 1:
                $where['q.astr_id'] = $this->astrInfo['id'];
                if ($param['qtype'])
                {
                    foreach ($param['qtype']['qtype'] as $k => $v)
                    {
                        $qtype['qtype']['qtype'][$k] = (int)$v;
                    }
                    $where['q.qtype'] = ['in', $qtype['qtype']['qtype']];
                }

                if ($param['status'])
                {
                    if (is_array($param['status']['status']))
                    {
                        foreach ($param['status']['status'] as $k => $v)
                        {
                            $param['status']['status'][$k] = (int)$v;
                        }
                        if ($param['status']['status'][0] === 5)
                        {//如果是已完成，那么把评价待审核和已评价也加上
                            $param['status']['status'][] = 6;
                            $param['status']['status'][] = 7;
                        }
                        $where['q.status'] = ['in', $param['status']['status']];
                    } else
                    {
                        $status = [];
                        foreach ($param['status'] as $k => $v)
                        {
                            $status[] = (int)$v;
                        }
                        if ($status[0] === 5)
                        {//如果是已完成，那么把评价待审核和已评价也加上
                            $status[] = 6;
                            $status[] = 7;
                        }
                        $where['q.status'] = ['in', $status];
                    }

                }

                if ($param['question'])
                {
                    $where['q.question_name'] = ['like', '%' . $param['question'] . '%'];
                }

                $resData = Db::table('wechat_backup_07_18_14_43_00.zlcr_custom_report_question')->alias('q')
                    ->join('wechat_backup_07_18_14_43_00.zlcr_astr_account_record a', 'a.qid=q.id')
                    ->where($where)->order('a.create_time desc')
                    ->field('q.id qid,q.question_name question,q.astr_receiving_time,a.amount earnings,q.status,q.qtype,q.is_merge,q.is_back,q.check_time1,q.check_time2,q.answer_time,a.proportion,q.invalid_time,a.type zlcr_astr_account_record_type,a.create_time')
                    ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();

                $dataList = [];
                foreach ($resData['data'] as $key => $datum)
                {
                    // 定制报告
                    $dataList[] = [
                        'task_id' => $datum['qid'],
                        'qid' => $datum['qid'],
                        'question_type' => 4,
                        'question' => $datum['question'],
                        'astr_receiving_time' => $datum['astr_receiving_time'],
                        'create_time' => $datum['create_time'],
                        'earnings' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? 0 : $datum['earnings'],
                        'status_des' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? '未完成' : '完成任务',
                        'proportion' => $datum['proportion'],
                        'is_merge' => $datum['is_merge'] ?? '',
                        'qtype' => $datum['qtype'],
                        'answer_time' => $datum['answer_time'],
                        'check_time2' => $datum['check_time2'],
                    ];
                }
                break;
            case 2:
                $where['q.astr_id'] = $this->astrInfo['id'];
                if ($param['status'])
                {   // 状态筛选

                }

                if ($param['question'])
                {
                    $where['q.question'] = ['like', '%' . $param['question'] . '%'];
                }
                $resData = Db::table('wechat_backup_07_18_14_43_00.zlcr2_user_question')->alias('q')
                    ->join('wechat_backup_07_18_14_43_00.zlcr_astr_account_record a', 'a.qid=q.id')
                    ->where($where)->order('a.create_time desc')
                    ->field('q.id qid,q.question,q.astr_receiving_time,a.amount earnings,q.status,q.question_type,q.is_synastry,a.proportion,a.type zlcr_astr_account_record_type,q.lock_reason,a.create_time')
                    ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();

                $dataList = [];
                foreach ($resData['data'] as $key => $datum)
                {
                    $dataList[] = [
                        'task_id' => Db::table('wechat_backup_07_18_14_43_00.zlcr2_astr_tasks')->where(['astr_id' => $this->astrInfo['id'], 'qid' => $datum['qid']])->value('id'),
                        'qid' => $datum['qid'],
                        'question_type' => (int)$datum['question_type'],
                        'question' => $datum['question'],
                        'astr_receiving_time' => $datum['astr_receiving_time'],
                        'create_time' => $datum['create_time'],
                        'earnings' => $datum['earnings'],
                        'status_des' => $datum['lock_reason'] ? '扣除收益：' . $datum['lock_reason'] : '完成任务',
                        'proportion' => $datum['proportion'],
                        'is_merge' => $datum['is_synastry'] ?? '',
                        'qtype' => 0,
                        'answer_time' => 0,
                        'check_time2' => 0,
                    ];
                }
                break;
            default:
                $astrId = $this->astrInfo['id'];
                // $resData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->alias('a')
                //     ->join('wechat_backup_07_18_14_43_00.zlcr2_user_question q1', 'a.qid=q1.id', 'left')
                //     ->join('wechat_backup_07_18_14_43_00.zlcr_custom_report_question q2', 'a.qid=q2.id', 'left')
                //     ->where($where)->where(function ($query) use ($astrId)
                //     {
                //         $query->where('q1.astr_id', $astrId)->whereor('q2.astr_id', $astrId);
                //     })->order('a.create_time desc')
                //     ->field('a.qid,q1.question question1,q2.question_name question2,q1.astr_receiving_time astr_receiving_time1,q2.astr_receiving_time astr_receiving_time2,a.amount earnings,q1.status status1,q2.status status2,q1.question_type,a.question_type question_type_record,q1.is_synastry,q2.is_merge,a.proportion,a.type zlcr_astr_account_record_type,q1.lock_reason,a.create_time,q2.qtype,q2.answer_time,q2.check_time2')
                //     ->paginate(['page' => $param['page'], 'list_rows' => $param['limit']])->toArray();
                // 流水总数
                $totalNum = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->alias('a')
                    ->where($where)->where(['a.astr_id' => $astrId, 'type' => ['in', [1, 4, 5]]])
                    ->count();

                $resData = getPaginatorData($totalNum, 1, 10);

                $resData['data'] = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->alias('a')
                    ->join('good_wechat.zyhs_consult_chat_rtc_record rtc', 'a.gid=rtc.id', 'left')
                    ->join('wechat_backup_07_18_14_43_00.zlcr2_user_question q1', 'a.qid=q1.id', 'left')
                    ->join('wechat_backup_07_18_14_43_00.zlcr_custom_report_question q2', 'a.qid=q2.id', 'left')
                    ->where($where)->where(['a.astr_id' => $astrId, 'a.type' => ['in', [1, 4, 5]]])->order('a.create_time desc')
                    ->field('a.qid,q1.question question1,q2.question_name question2,q1.astr_receiving_time astr_receiving_time1,q2.astr_receiving_time astr_receiving_time2,a.amount earnings,q1.status status1,q2.status status2,q1.question_type,a.question_type question_type_record,q1.is_synastry,q2.is_merge,a.proportion,a.type zlcr_astr_account_record_type,q1.lock_reason,a.create_time,q2.qtype,q2.answer_time,q2.check_time2,rtc.eff_duration,rtc.unit_price,rtc.id rtc_id,rtc.chat_detail_id')
                    ->limit($resData['start'], $resData['end'])->select();

                $dataList = [];
                foreach ($resData['data'] as $key => $datum)
                {
                    switch ($datum['question_type_record'])
                    {
                        case 1: // 定制报告
                            $dataList[] = [
                                'task_id' => (int)$datum['qid'],
                                'qid' => (int)$datum['qid'],
                                'question_type' => 4,
                                'question' => $datum['question2'],
                                'astr_receiving_time' => (int)$datum['astr_receiving_time2'],
                                'create_time' => (int)$datum['create_time'],
                                'earnings' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? 0 : $datum['earnings'],
                                'status_des' => (int)$datum['zlcr_astr_account_record_type'] === 3 ? '未完成' : '完成任务',
                                'proportion' => $datum['proportion'],
                                'is_merge' => (int)($datum['is_merge'] ?? 0),
                                'qtype' => $datum['qtype'],
                                'answer_time' => $datum['answer_time'],
                                'check_time2' => $datum['check_time2'],
                            ];
                            break;
                        case 2: // 问答
                            $dataList[] = [
                                'task_id' => (int)Db::table('wechat_backup_07_18_14_43_00.zlcr2_astr_tasks')->where(['astr_id' => $this->astrInfo['id'], 'qid' => $datum['qid']])->value('id'),
                                'qid' => (int)$datum['qid'],
                                'question_type' => (int)$datum['question_type'],
                                'question' => $datum['question1'],
                                'astr_receiving_time' => (int)$datum['astr_receiving_time1'],
                                'create_time' => (int)$datum['create_time'],
                                'earnings' => $datum['earnings'],
                                'status_des' => $datum['lock_reason'] ? '扣除收益：' . $datum['lock_reason'] : '完成任务',
                                'proportion' => $datum['proportion'],
                                'is_merge' => (int)($datum['is_synastry'] ?? 0),
                                'qtype' => 0,
                                'answer_time' => 0,
                                'check_time2' => 0,
                            ];
                            break;
                        case 3: // 连线咨询
                            $dataList[] = [
                                'task_id' => (int)$datum['chat_detail_id'],
                                'qid' => (int)$datum['chat_detail_id'],
                                'question_type' => 5,
                                'question' => '计价时长：' . (Util::secondToMinute($datum['eff_duration'])) . '(单价：' . ($datum['unit_price'] / 10 * $datum['proportion']) . "元/分钟)",
                                'astr_receiving_time' => '',
                                'create_time' => (int)$datum['create_time'],
                                'earnings' => $datum['earnings'],
                                'status_des' => '完成任务',
                                'proportion' => $datum['proportion'],
                                'is_merge' => 0,
                                'qtype' => 0,
                                'answer_time' => 0,
                                'check_time2' => 0,
                            ];
                            break;
                    }
                }
        }

        // 计算团队 至今总收益 以及 未提现金额
        if ($teamId)
        {   // 团队 占星师个人 总收益
            $teamTotalAmount = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'team_id' => $teamId])->sum('amount');
            // 团队 占星师个人 未提现总余额
            $teamBalance = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->where(['astr_id' => $this->astrInfo['id'], 'type' => 1, 'team_id' => $teamId, 'is_withdrawal' => 0])->sum('amount');
        } else
        {
            $teamTotalAmount = 0;
            $teamBalance = 0;
        }

        if ($isTeam === 1)
        {   // 未结算
            $balance = $teamBalance;
            $totalAmount = $teamTotalAmount;
        } else
        {
            $balance = $accountInfo['balance'] - $teamBalance; // 当前余额 - 团队未结算金额 =  个人余额（个人未结算金额）
            $totalAmount = $accountInfo['total_amount'] - $teamTotalAmount; // 当前总收益 - 团队个人总收益 = 个人结算中总收益
        }

        $resData['data'] = $dataList;
        $resData['balance'] = (string)$balance;
        $resData['earn_all'] = (string)$totalAmount;
        $resData['is_team'] = $teamId > 0 ? 1 : 0;

        return show(200, '请求成功', $resData);
    }
}
